<template>
  <view class="page-container">
    <!-- 页面标题 -->
    <view class="header-title">
      健康监测
    </view>

    <!-- 健康指标列表 -->
    <!-- 修改点：v-for现在遍历的是计算属性 displayMetrics -->
    <view class="metric-list">
      <view v-for="item in displayMetrics" :key="item.id" class="metric-card" :style="{ backgroundColor: item.bgColor }" @click="queryHistory(item)">
        <view class="card-left">
          <image class="metric-icon" :src="item.icon" mode="aspectFit"></image>
          <view class="metric-info">
            <text class="metric-name">{{ item.name }}</text>
            <text class="metric-time">{{ item.time }}</text>
          </view>
        </view>
        <view class="card-right">
          <view class="metric-value">
            <text class="value">{{ item.value }}</text>
            <text class="unit">{{ item.unit }}</text>
          </view>
          <view class="status-tag" :class="item.status === '正常' ? 'normal' : 'abnormal'">
            {{ item.status }}
          </view>
        </view>
      </view>
    </view>

    <view class="tips">
      <text>点击卡片查看历史数据趋势</text>
    </view>
  </view>
</template>

<script>
// 新增点：将静态的显示配置（图标、颜色）独立出来
import {
  queryHealthMetrics
} from "../../api/metrices";
import {
  mapState
} from 'vuex';

const METRIC_CONFIG = {
  '体重': {
    icon: 'https://img.icons8.com/fluency/96/scale.png',
    bgColor: '#e0f3ff' // 浅蓝色
  },
  '血糖': {
    icon: 'https://img.icons8.com/fluency/96/diabetes.png',
    bgColor: '#ffe6e9' // 浅红色
  },
  '血压': {
    icon: '../../static/blood-press.jpg',
    bgColor: '#dff9eb' // 浅绿色
  },
  '心率': {
    icon: 'https://img.icons8.com/fluency/96/like.png',
    bgColor: '#fff4e0' // 浅橙色
  }
};

export default {
  name: "HeathObserve",
  data() {
    return {
      // healthMetrics 的初始值可以为空数组，等待接口加载
      healthMetrics: []
    };
  },
  computed: {
    ...mapState({
      // 用户信息
      user: state => state.userInfo
    }),
    displayMetrics() {
      // 如果 healthMetrics 为空，直接返回空数组，防止 map 出错
      if (!this.healthMetrics || this.healthMetrics.length === 0) {
        return [];
      }
      return this.healthMetrics.map(metric => {
        return {
          ...metric, // 动态数据
          ...METRIC_CONFIG[metric.name] // 根据名称匹配并合并静态配置
        };
      });
    }
  },
  onLoad() {
    this.queryMetrics();
  },
  methods: {
    /**
     * 【核心修改】
     * 查询并处理健康数据
     */
    async queryMetrics() {
      try {
        // 假设 queryHealthMetrics 返回的数据结构就是你提供的 JSON
        console.log(this.user)
        let { data: responseData } = await queryHealthMetrics(this.user.residentId);
        console.log('从后台获取的原始数据:', responseData);

        // 后台返回的原始数据对象
        const records = responseData.data;

        // 创建一个新数组用于存放转换后的数据
        const transformedMetrics = [];

        // 1. 处理体重数据
        if (records.weightRecords) {
          transformedMetrics.push({
            id: 1,
            name: '体重',
            value: records.weightRecords.weightValue,
            unit: 'Kg',
            time: this.formatDate(records.weightRecords.measurementDate),
            status: this.getWeightStatus(records.weightRecords.weightValue),
          });
        }

        // 2. 处理血糖数据
        if (records.bloodGlucoseRecords) {
          transformedMetrics.push({
            id: 2,
            name: '血糖',
            value: records.bloodGlucoseRecords.glucoseValue,
            unit: 'mmol/L',
            time: this.formatDate(records.bloodGlucoseRecords.measurementDate),
            status: this.getBloodGlucoseStatus(records.bloodGlucoseRecords.glucoseValue, records.bloodGlucoseRecords.measurementType),
          });
        }

        // 3. 处理血压数据
        if (records.bloodPressureRecords) {
          transformedMetrics.push({
            id: 3,
            name: '血压',
            // 将收缩压和舒张压合并成一个字符串
            value: `${records.bloodPressureRecords.systolicPressure}/${records.bloodPressureRecords.diastolicPressure}`,
            unit: 'mmHg',
            time: this.formatDate(records.bloodPressureRecords.measurementDate),
            status: this.getBloodPressureStatus(records.bloodPressureRecords.systolicPressure, records.bloodPressureRecords.diastolicPressure),
          });
        }

        // 4. 处理心率数据
        if (records.heartRateRecords) {
          transformedMetrics.push({
            id: 4,
            name: '心率',
            value: records.heartRateRecords.heartRate,
            unit: 'bpm',
            time: this.formatDate(records.heartRateRecords.measurementDate),
            status: this.getHeartRateStatus(records.heartRateRecords.heartRate),
          });
        }
        // 5. 将转换后的数据赋值给 healthMetrics，触发页面更新
        this.healthMetrics = transformedMetrics;
        console.log('转换后用于绑定的数据:', this.healthMetrics);
      } catch (error) {
        console.error("获取健康数据失败:", error);
      }
    },

    /**
     * 【新增】
     * 格式化日期时间，将 'T' 替换为空格
     */
    formatDate(dateTimeString) {
      if (!dateTimeString) return '';
      return dateTimeString.replace('T', ' ');
    },

    /**
     * 【以下为新增的状态判断逻辑，你可以根据实际的医学标准进行调整】
     */
    getWeightStatus(value) {
      if (value > 90) return '偏高';
      if (value < 50) return '偏低';
      return '正常';
    },

    getBloodGlucoseStatus(value, type) {
      // 餐前血糖正常范围: 3.9 - 6.1 mmol/L
      if (type === '餐前') {
        if (value > 6.1) return '偏高';
        if (value < 3.9) return '偏低';
        return '正常';
      }
      // 餐后血糖等其他情况可以继续添加
      return '正常'; // 默认值
    },

    getBloodPressureStatus(systolic, diastolic) {
      // 正常范围：收缩压 < 140 AND 舒张压 < 90
      if (systolic >= 140 || diastolic >= 90) {
        return '偏高';
      }
      if (systolic < 90 || diastolic < 60) {
        return '偏低';
      }
      return '正常';
    },

    getHeartRateStatus(value) {
      // 正常范围: 60 - 100 bpm
      if (value > 100) return '偏高';
      if (value < 60) return '偏低';
      return '正常';
    },

    queryHistory(item) {
      // 点击后跳转到对应指标的详情页
      console.log('查看详情:', item.name);
      uni.navigateTo({
        url: `/pages/health/health-history?type=${item.name}`
      });
    }
  }
}
</script>

<style scoped>
/* 页面整体样式 */
.page-container {
  background-color: #f5f8ff;
  min-height: 100vh;
  padding: 30rpx;
}

/* 页面标题 */
.header-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
}

/* 指标列表 */
.metric-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  /* 卡片之间的间距 */
}

/* 指标卡片 */
.metric-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
  transition: transform 0.2s ease-in-out;
}

.metric-card:active {
  transform: scale(0.98);
  /* 点击时有轻微缩小效果 */
}

.card-left {
  display: flex;
  align-items: center;
}

.metric-icon {
  width: 80rpx;
  height: 80rpx;
  margin-right: 24rpx;
}

.metric-info {
  display: flex;
  flex-direction: column;
}

.metric-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.metric-time {
  font-size: 24rpx;
  color: #888;
  margin-top: 8rpx;
}

.card-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.metric-value {
  display: flex;
  align-items: baseline;
}

.value {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.unit {
  font-size: 24rpx;
  color: #666;
  margin-left: 8rpx;
}

.status-tag {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-top: 8rpx;
}

.status-tag.normal {
  background-color: #dff9eb;
  color: #2b8a3e;
}

.status-tag.abnormal {
  background-color: #ffe6e9;
  color: #c92a2a;
}

.tips {
  text-align: center;
  color: #aaa;
  font-size: 24rpx;
  margin-top: 40rpx;
}
</style>

